import 'dart:async';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';

import '../../config/app_data_config.dart';
import '../../ui/dialog/dailog.dart';
import '../bean/http_data.dart';
import '../bean/works_2023/purcontract_bean.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../sign.dart';
import '../url.dart';

///物料编码
// {
// "IsSuccess": true,
// "MsgDetail": "获得自定义编码规则成功！",
// "MsgCode": 100,
// "Data": [{
// "Id": 5569,
// "CodeId": "GlassMaterialCode",
// "CodeName": "原片自定义物料编码",
// "ItemCode": "29",
// "ItemName": "规格尺寸",
// "ItemValue": "",
// "OrderId": 1,
// "Status": 0,
// "CodeGroup": "",
// "isUpdate": 1
// }, {
// "Id": 5570,
// "CodeId": "GlassMaterialCode",
// "CodeName": "原片自定义物料编码",
// "ItemCode": "28",
// "ItemName": "供应商",
// "ItemValue": "",
// "OrderId": 2,
// "Status": 0,
// "CodeGroup": "",
// "isUpdate": 1
// }, {
// "Id": 5571,
// "CodeId": "GlassMaterialCode",
// "CodeName": "原片自定义物料编码",
// "ItemCode": "01",
// "ItemName": "固定字符",
// "ItemValue": "YP",
// "OrderId": 3,
// "Status": 0,
// "CodeGroup": "",
// "isUpdate": 1
// }]
// }
///物料编码
class GlassMaterialCode extends BaseBean {
  String? Id = "";
  String? CodeId = "";
  String? CodeName = "";
  String? ItemCode = "";
  String? ItemName = "";
  String? ItemValue = "";
  String? OrderId = "";
  String? Status = "";
  String? CodeGroup = "";
  String? isUpdate = "";

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    Id = json["Id"]?.toString() ?? "";
    CodeId = json["CodeId"]?.toString() ?? "";
    CodeName = json["CodeName"]?.toString() ?? "";
    ItemCode = json["ItemCode"]?.toString() ?? "";
    ItemName = json["ItemName"]?.toString() ?? "";
    ItemValue = json["ItemValue"]?.toString() ?? "";
    OrderId = json["OrderId"]?.toString() ?? "";
    Status = json["Status"]?.toString() ?? "";
    CodeGroup = json["CodeGroup"]?.toString() ?? "";
    isUpdate = json["isUpdate"]?.toString() ?? "";
  }

  @override
  Map<String, dynamic> toJson() {
    // TODO: implement toJson
    var map = <String, dynamic>{};
    map["Id"] = Id;
    map["CodeId"] = CodeId;
    map["CodeName"] = CodeName;
    map["ItemCode"] = ItemCode;
    map["ItemName"] = ItemName;
    map["ItemValue"] = ItemValue;
    map["OrderId"] = OrderId;
    map["Status"] = Status;
    map["CodeGroup"] = CodeGroup;
    map["isUpdate"] = isUpdate;
    return map;
  }

  @override
  instance() {
    // TODO: implement instance
    return GlassMaterialCode();
  }
}

///来源类型
// {
// "DataId": 1546,
// "TypeName": "来源类型",
// "TypeCode": "SourceType",
// "ItemName": "国产",
// "ItemCode": "01",
// "OrderId": 3,
// "IsUse": 1,
// "AddDate": "2021-06-07T10:32:10.49",
// "EditDate": "2024-07-12T09:26:09.79",
// "IsSystem": 0,
// "OtherCode": "g",
// "ItemIntro": "",
// "ItemGroup": ""
// }
class SourceTypeInfo extends BaseBean {
  String? ItemCode = "";
  String? ItemName = "";
  String? CodeName = "";
  String? OtherCode = "";
  String? IsUse = "";

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    CodeName = json["CodeName"]?.toString() ?? "";
    ItemCode = json["ItemCode"]?.toString() ?? "";
    ItemName = json["ItemName"]?.toString() ?? "";
    OtherCode = json["OtherCode"]?.toString() ?? "";
    IsUse = json["IsUse"]?.toString() ?? "";
  }

  @override
  Map<String, dynamic> toJson() {
    // TODO: implement toJson
    var map = <String, dynamic>{};
    map["CodeName"] = CodeName;
    map["ItemCode"] = ItemCode;
    map["ItemName"] = ItemName;
    map["OtherCode"] = OtherCode;
    map["IsUse"] = IsUse;
    return map;
  }

  @override
  instance() {
    // TODO: implement instance
    return SourceTypeInfo();
  }
}

class AjaxSalesModel {
  static Map<String, List<GlassMaterialCode>> _map =
      <String, List<GlassMaterialCode>>{}; //缓存物料编码规则
  static Map<String, String> _mapStr = <String, String>{}; //缓存，品牌，类型，大类的编码规则。

  ///清除缓存
  static clear() {
    _map?.clear();
    _mapStr?.clear();
  }

  ///获取物料编码规则
  ///物料类型 MaterialType,  MT01：原片 MT02：辅料 MT03：五金
  static Future<AppHttpResult<List<GlassMaterialCode>, GlassMaterialCode>>
      _getAjaxSales(BuildContext context, bool isEnableLoad,
          {String? MaterialType}) async {
    Completer completer = new Completer<
        AppHttpResult<List<GlassMaterialCode>, GlassMaterialCode>>();
    var url = Url.baseurl() + Url.AjaxSales;
    // print("${Url.baseurl()}");
    // print("url:$url");//url:http://192.168.1.5:8082//App/Android/AjaxSales.ashx
    var token = AppDataConfig.getToken();
    var type = "GlassMaterialCode";
    if (MaterialType == "MT01") {
      //原片
      type = "GlassMaterialCode";
    } else if (MaterialType == "MT02") {
      //辅料
      type = "AccMaterialCode";
    } else if (MaterialType == "MT03") {
      //五金
      type = "MaterMaterialCode";
    }
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata = '''{"type":"$type"}''';
    var queryParameters = Map<String, dynamic>();
    //queryParameters['data'] = subData.jsonEncodeToJson();
    var data = '''{"type":"$type"}''';
    queryParameters['data'] = data;
    //print('提交数据：$data');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        //print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('物料编码规则:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isAllowedRepeat = true //允许重复提交，会存在多个同时提交的情况。
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<GlassMaterialCode>, GlassMaterialCode>>(
              AppHttpResult()
                ..Data = <GlassMaterialCode>[]
                ..t2 = GlassMaterialCode())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<GlassMaterialCode>, GlassMaterialCode>>;
  }

  ///获取物料编码
  ///MaterialType 品牌传4；Id就传品牌id
  static Future<String?> _getAjaxStore(BuildContext context, bool isEnableLoad,
      {String? MaterialType, String? Id}) async {
    Completer completer = new Completer<String?>();
    var url = Url.baseurl() + Url.AjaxStore;
    // print("${Url.baseurl()}");
    // print("url:$url"); //url:http://192.168.1.5:8082//App/Android/AjaxSales.ashx
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata = '''{"MaterialType":"$MaterialType","Id":"$Id"}''';
    var queryParameters = Map<String, dynamic>();
    //queryParameters['data'] = subData.jsonEncodeToJson();
    var data = '''{"MaterialType":"$MaterialType","Id":"$Id"}''';
    var rst = _mapStr[data];
    // print("=====================rst:$rst");
    if (StringUtils.isNotEmpty(rst)) {
      return Future.value(rst); //fixme 判断本地是否有缓存，如果有，直接返回。
    }
    queryParameters['data'] = data;
    // print('获取物料编码提交数据：$data');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('获取物料编码数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isAllowedRepeat = true //允许重复提交，会存在多个同时提交的情况。
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<String>("")?.then((result) {
        _mapStr[data] = result; //fixme 缓存数据，节省接口调用。
        completer.complete(result);
      });
    return completer.future as Future<String?>;
  }

  ///获取物料编码
  static _getAjaxSalesGlassMaterialCode(BuildContext context, bool isEnableLoad,
      {String? MaterialType,
      ResponseCallbackWithT<List<GlassMaterialCode>>? callbackWith}) async {
    if (MaterialType != null) {
      var data = _map[MaterialType!];
      if (data != null) {
        callbackWith?.call(data);
      } else {
        _getAjaxSales(context, isEnableLoad, MaterialType: MaterialType)
            ?.then((value) {
          if (value.isSuccessForData()) {
            _map[MaterialType!] = value.Data!; //保存起来，不用频繁的调接口。
            callbackWith?.call(value.Data!);
          }
        });
      }
    }
  }

  ///获取物料编码
  ///SupplierId 供应商id
  ///sourceTypeItemCode 用户当前选中的来源类型。
  static getMaterialNumber(
      String SupplierId, BuildContext context, bool isEnableLoad,
      {PurDemand? data = null,
      ResponseCallbackWithString? callback = null,
      String sourceTypeItemCode = "01"}) async {
    String width = data?.Width ?? ""; //宽
    String height = data?.Height ?? ""; //高
    String MaterialType = data?.MaterialType ?? ""; //物料类型
    String MaterialTypeCode = data?.MaterialTypeCode ?? "";
    String MaterialTypeId = data?.MaterialTypeId ?? ""; //类型id
    String ManufacturerId = data?.ManufacturerId ?? ""; //品牌id
    String Size = data?.Size ?? ""; //规格
    _getAjaxSalesGlassMaterialCode(context, isEnableLoad,
        MaterialType: MaterialType, callbackWith: (value) async {
      var MaterialCode = ""; //物料编码
      var datas = value; //规则
      var is36 = false; //是否允许特殊字符（除数值和字母以外都是特殊字符），不允许特殊字符时：小数点后面都不要(包括小数点)；
      datas?.forEach((element) {
        if (element.ItemCode == "36") {
          is36 = true;
        }
      });
      var branch = await _getBranch(context, false,
          Id: ManufacturerId, MaterialTypeCode: MaterialTypeCode); //品牌
      var type = await _getType(context, false,
          MaterialType: MaterialType,
          Id: MaterialTypeId,
          MaterialTypeCode: MaterialTypeCode); //类型
      var broadCategory = await _getBroadCategory(context, false,
          MaterialType: MaterialType,
          Id: MaterialTypeId,
          MaterialTypeCode: MaterialTypeCode); //大类
      var supplier = await _getSupplier(context, false, Id: SupplierId); //供应商
      var sourceType = await getSourceType(context, false,
          sourceTypeItemCode: sourceTypeItemCode); //
      // print("============================品牌：$branch");
      //类型 + 供应商 + 规格尺寸 + 品牌 + 大类
      datas?.forEach((element) {
        // print("============================循环：$MaterialCode\t${element.ItemCode}");
        switch (element.ItemCode) {
          case "01": //固定字符
            MaterialCode += element.ItemValue ?? "";
            // print("固定字符：${element.ItemValue}");
            break;
          case "30": //品牌 4 品牌id
            MaterialCode += branch;
            // print("============================品牌：$MaterialCode");
            // print("品牌：${branch}");
            break;
          case "29": //尺寸
            if (MaterialType == "MT03") {
              //五金使用 Size
              if (is36) {
                //允许特殊字符
                MaterialCode += Size;
                // print("允许特殊字符(五金)：${Size}");
              } else {
                //不允许特殊字符
                if (StringUtils.isNotEmpty(Size)) {
                  var Size2 = Size!.split(".")[0];
                  var Size3 = RegexUtils.getNumberOrLetter(Size2);
                  MaterialCode += Size3;
                  // print("不允许特殊字符(五金)：${Size2}\t${Size3}");
                }
              }
            } else {
              if (is36) {
                //允许特殊字符
                MaterialCode += width.toString();
                MaterialCode += height.toString();
                // print("允许特殊字符：${width.toString()}\t${height.toString()}");
              } else {
                //不允许特殊字符
                if (StringUtils.isNotEmpty(width)) {
                  var w = double.parse(width);
                  MaterialCode += w.toInt().toString();
                  // print("不允许特殊字符width：${w.toInt().toString()}");
                }
                if (StringUtils.isNotEmpty(height)) {
                  var h = double.parse(height);
                  MaterialCode += h.toInt().toString();
                  // print("不允许特殊字符height：${h.toInt().toString()}");
                }
              }
            }
            break;
          case "36": //允许特殊字符，既:允许小数点。
            break;
          case "27": //类型 ====1,2,3 ；id传 MaterialTypeId
            MaterialCode += type;
            // print("类型：${type}");
            break;
          case "31": //大类=====7,8,9 id传 MaterialTypeId
            MaterialCode += broadCategory;
            // print("大类：${broadCategory}");
            break;
          case "28": //供应商
            MaterialCode += supplier;
            // print("供应商：${supplier}");
            break;
          case "32": //来源类型
            MaterialCode += sourceType ?? "";
            break;
          case "34": //是否来料
          default:
            break;
        }
      });
      // print("============================最终：$MaterialCode");
      callback?.call(MaterialCode);
    });
  }

  //接口，返回品牌编码
  static Future<String> _getBranch(BuildContext context, bool isEnableLoad,
      {String? MaterialType = "4",
      String? Id,
      String? MaterialTypeCode}) async {
    if (MaterialType == "MT03") {
      //五金
      MaterialType = "3";
      Id = MaterialTypeCode; //fixme 五金用code
    }
    var value = await _getAjaxStore(context, isEnableLoad,
        MaterialType: MaterialType, Id: Id);
    // print("品牌返回：\t$value");
    return value ?? "";
  }

  //接口，返回类型
  static Future<String> _getType(BuildContext context, bool isEnableLoad,
      {String? MaterialType, String? Id, String? MaterialTypeCode}) async {
    if (MaterialType == "MT01") {
      //原片
      MaterialType = "1";
    }
    if (MaterialType == "MT02") {
      //辅料
      MaterialType = "2";
    }
    if (MaterialType == "MT03") {
      //五金
      MaterialType = "3";
      Id = MaterialTypeCode; //fixme 五金用code
    }
    var value = await _getAjaxStore(context, isEnableLoad,
        MaterialType: MaterialType, Id: Id);
    // print("类型返回：\t$value");
    return value ?? "";
  }

  //接口，大类
  static Future<String> _getBroadCategory(
      BuildContext context, bool isEnableLoad,
      {String? MaterialType, String? Id, String? MaterialTypeCode}) async {
    if (MaterialType == "MT01") {
      //原片
      MaterialType = "7";
    }
    if (MaterialType == "MT02") {
      //辅料
      MaterialType = "8";
    }
    if (MaterialType == "MT03") {
      //五金
      MaterialType = "9";
      Id = MaterialTypeCode; //fixme 五金用code
    }
    var value = await _getAjaxStore(context, isEnableLoad,
        MaterialType: MaterialType, Id: Id);
    // print("大类返回：\t$value");
    return value ?? "";
  }

  //接口，返回供应商编码
  static Future<String> _getSupplier(BuildContext context, bool isEnableLoad,
      {String? MaterialType = "5", String? Id}) async {
    var value = await _getAjaxStore(context, isEnableLoad,
        MaterialType: MaterialType, Id: Id);
    // print("品牌返回：\t$value");
    return value ?? "";
  }

  //接口，获取来源类型
  static Future<String?> getSourceType(BuildContext context, bool isEnableLoad,
      {String sourceTypeItemCode = "01"}) async {
    var _key = "sourceTypeItemCode_${sourceTypeItemCode}";
    Completer completer = new Completer<String?>();
    var url = Url.baseurl() + Url.AjaxPurchase;
    // print("${Url.baseurl()}");
    // print("url:$url"); //url:http://192.168.1.5:8082//App/Android/AjaxSales.ashx
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    // subData.ReviewType = AuditManager.item!.ReviewType!; //审核类型
    // subData.businessdata = AuditManager.ReviewTypeId; //审核类型ID
    // subData.YwxId = AuditManager.YwxId;
    // subData.YwxName = AuditManager.YwxName;
    // subData.Status = Status; //审核状态
    // subData.Intro = Intro; //审核意见
    subData.ReviewType = "GetSourceType"; //获取来源类型
    var rst = _mapStr[_key];
    // print("=====================rst:$rst");
    if (StringUtils.isNotEmpty(rst)) {
      return Future.value(rst); //fixme 判断本地是否有缓存，如果有，直接返回。
    }
    var queryParameters = Map<String, dynamic>();
    queryParameters['data'] = subData.jsonEncodeToJson();
    // print('物料请购提交数据：${subData.jsonEncodeToJson()}');
    // return Future.value(null);
    //print("================================================token:$token");
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // [{"ItemCode":"02","ItemName":"进口"},{"ItemCode":"01","ItemName":"国产"}]
        // print('来源类型数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isAllowedRepeat = true //允许重复提交，会存在多个同时提交的情况。
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postListASync<List<SourceTypeInfo>, SourceTypeInfo>(<SourceTypeInfo>[],
              t2: SourceTypeInfo())
          ?.then((result) {
        // print("==============result:\t$result");
        String _result = "";
        result?.forEach((element) {
          // print(
          //     "${element.ItemCode}\t${sourceTypeItemCode}\t${element.OtherCode}");
          if (element.ItemCode == sourceTypeItemCode) {
            _result = element.OtherCode ?? "";
          }
        });
        if (StringUtils.isNotEmpty(_result)) {
          _mapStr[_key] = _result; //fixme 缓存数据，节省接口调用。
        }
        completer.complete(_result);
      });
    return completer.future as Future<String?>;
  }
}
